<?php

namespace App\Jobs\Train\Snap;

use App\Models\Task\SnapTasks\Repositories\SnapTaskTrip;
use App\Models\Task\SnapTasks\SnapTask;
use App\Trip\Train\Order\Impl\SnapTaskLowLevel\SnapTaskLowLevelImpl;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ProcessSnapTaskLowLevel implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    private SnapTask     $task;
    private SnapTaskTrip $trip;

    public function __construct(SnapTask $task, SnapTaskTrip $trip)
    {
        $this->task = $task;
        $this->trip = $trip;
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws Exception
     */
    public function handle()
    {
        Log::info("低速抢票开始:TaskId:{$this->task->getTaskId()}:trip_index:{$this->trip->getTaskTripIndex()}");

        $task = $this->task->refresh();
        if ($task->getTaskState() != SnapTask::TASK_STATE_SNAPPING) {
            Log::info("低速抢票开始:TaskId:{$task->getTaskId()}:trip_index:{$this->trip->getTaskTripIndex()},任务状态已变更停止抢票");
            throw new Exception("任务状态已变更停止抢票,{$this->task->getTaskId()}");
        }

        if ($task->getSnapState() != SnapTask::SNAP_STATE_STARTED) {
            Log::info("低速抢票开始:TaskId:{$task->getTaskId()}:trip_index:{$this->trip->getTaskTripIndex()},抢票状态:{$task->getSnapState()}");
            throw new Exception("任务当前抢票状态变更,{$this->task->getTaskId()}");
        }


        $sl       = new SnapTaskLowLevelImpl($this->task->getTaskId(), 'ticket');
        $order_id = "";
        try {
            $order_id = $sl->ticket($this->trip);
        } catch (Exception $exception) {
            Log::error("低速抢票任务链:异常则继续下一个子行程,{$exception->getMessage()}");
        }


        if ($order_id) {
            Log::error("低速抢票任务链:已刷上票,trip_index:{$this->trip->getTaskTripIndex()},task_id:{$this->task->getTaskId()},order_id:{$order_id},停止任务链");
            throw new Exception("任务已刷上票,{$this->task->getTaskId()}");
        }

    }
}
